package networking;

import java.io.*;
import java.net.*;

public class Sender implements Runnable {
	
	private int port;
	private String hostname;
	Socket kkSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
	
	public Sender(int portNum, String opponetHostname) throws IOException{
		this.port = portNum;
		this.hostname = opponetHostname;		
	System.out.println(port);
	System.out.println(hostname);
	}
		

	@Override
	public void run() {
		boolean retry = true;
		long sleep = 10000;
		while(retry == true){
			try {
	            kkSocket = new Socket(hostname, port);
	            out = new PrintWriter(kkSocket.getOutputStream(), true);
	           
	            retry = false;
	        } catch (UnknownHostException e) {
	            System.err.println("Don't know about host: " + hostname);
	            try {
					Thread.sleep(sleep);
				} catch (InterruptedException e1) {
					System.out.println("interrupted");
				}
	        } catch (IOException e) {
	        	System.err.println("Couldn't get I/O for the connection to: " + hostname);
	        	 try {
						Thread.sleep(sleep);
					} catch (InterruptedException e1) {
						System.out.println("interrupted");
					}
	        }
		}
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        
        String fromUser = "test";
        
        try {
			while (fromUser != "quit") {
			    
			    fromUser = stdIn.readLine();
				if (fromUser != null) {
				        System.out.println("ME: " + fromUser);
				        out.println(fromUser);
				}
			}
		} catch (IOException e) {			
			e.printStackTrace();
		}
        try {
        	out.close();
			stdIn.close();
			kkSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
	
